package com.nit.tools.document;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

/**
 * ok
 * pdf转图片
 */
public class PdfTools {

    public static void main(String[] args) {
        try {
            String destfile = "D://doc//doc_test//828080818EE0747C018EE0747D1B0000.pdf";
            PdfTools.loadPdf2Image("D://doc//doc_test//pdf_image//", destfile, 300, "jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * PDF文件转图片
     *
     * @param imageFolderPath 存放图片文件路径
     * @param pdfSourcePath   需要读取的pdf路径
     * @param dpi             这个越大，图片越清晰，300挺清楚了
     * @param formatName
     * @ return void
     */
    public static void loadPdf2Image(String imageFolderPath, String pdfSourcePath, int dpi, String formatName) throws Exception {
        File pdfSourceFile = new File(pdfSourcePath);
        PDDocument document = Loader.loadPDF(pdfSourceFile);
        PDFRenderer renderer = new PDFRenderer(document);
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage bufferedImage = renderer.renderImageWithDPI(i, dpi);
            String imagePath = imageFolderPath + pdfSourceFile.getName() + i + "." + formatName;
            FileOutputStream fileOutputStream = new FileOutputStream(imagePath);
            ImageIO.write(bufferedImage, formatName, fileOutputStream);
        }
        document.close();
        System.out.println("转换完成");
    }
}
